#coding: utf-8

import sys
import web
import time
import datetime
from web import form

import db
import skate as s
from libs import *
from config import app


__all__ = ['home', 'profile', 'activity', 'act_add', 'act_admin']


class activity:

    def handle_show_act(self, aid):
        try:
            act = db.get_act(aid)

            act['gathertime'] = act['gathertime'].strftime(
                    "%m月%d日 %H:%M")
            act['startime'] = act['startime'].strftime(
                    "%m月%d日 %H:%M")

            (wish, do) = db.get_act_rela(s.session.id, aid)
            act['user_wish'] = wish
            act['user_do'] = do
            act['creater'], act['creater_avatar'] = db.get_user_baseinfo(
                    act['uid'])

            return act
        except:
            raise web.notfound()

    def handle_interest(self, interest, aid):
        """user activity relation handle
        """
        try:
            db.handle_relation(s.session.id, aid, RELATION[interest])
        except KeyError:
            return

    def get_wish(self, aid):
        users = db.get_rel_act_wish(aid)

        tmp = []
        for i in users:
            j = {}
            j['nickname'], j['tiny_avatar'] = db.get_user_baseinfo(i['uid'])
            j['uid'] = i['uid']
            tmp.append(j)

        return tmp

    def get_do(self, aid):
        users = db.get_rel_act_do(aid)

        tmp = []
        for i in users:
            j = {}
            j['nickname'], j['tiny_avatar'] = db.get_user_baseinfo(i['uid'])
            j['uid'] = i['uid']
            tmp.append(j)

        return tmp

    def get_discuss(self, aid):
        return db.get_threads(aid=aid)
    
    def GET(self):
        input = web.input(aid=None, interest=None)
        try: 
            aid = int(input.aid)
        except ValueError:
            raise web.notfound()
    
        input = web.input(interest=None)
        if input.interest:
            self.handle_interest(input.interest, aid)

        act = self.handle_show_act(aid)
        liked = self.get_wish(aid)
        joined = self.get_do(aid)
        discuss = self.get_discuss(aid)

        return s.render.activity(act, liked, joined, discuss)

    def POST(self):
        pass

class add:

    activity_form = form.Form(
            form.Textbox('subject', form.notnull, description='活动标题'),
            form.Dropdown('type', ACTYPE, description='活动类型'),
            form.Textbox('basecredit', vnum, description='基础积分'),
            form.Textbox('gather_day', description='集合时间'),
            form.Dropdown('gather_hour', OURS, description=''),
            form.Dropdown('gather_min', MINS, description=''),
            form.Textbox('start_day', description='出发时间'),
            form.Dropdown('start_hour', OURS, description=''),
            form.Dropdown('start_min', MINS, description=''),
            form.Dropdown('gather_area',  AREA, description='集合区域'),
            form.Textbox('gather_location', description='集合地点'),
            form.Textbox('distance', form.notnull, description='距离'),
            form.Textarea('route', form.notnull, description='路线'),
            form.Textarea('descr', form.notnull, description='补充内容'),
            form.Hidden('aid', description=''),
            form.Hidden('x', description=''),
            form.Hidden('y', description=''),
            form.Hidden('acc', description=''),
            )
    
    def GET(self):
        
        f = self.activity_form()
        f['gather_location'].value="请在右边地图上拖动图标选择详细地址"
    
        return s.render.add_activity(f)

    def POST(self):

        f = self.activity_form()
        if not f.validates():
            s.session.show_msg = True
            s.session.msg = '添加活动失败'
            return s.render.add_activity(f)

        gather_time = '%s %s:%s' % (
                f['gather_day'].value, f['gather_hour'].value, f['gather_min'].value
                )

        start_time = '%s %s:%s' % (
                f['start_day'].value, f['start_hour'].value, f['start_min'].value
                )

        time_format = '%m/%d/%Y %H:%M'
        gather_time = datetime.datetime.fromtimestamp(
                time.mktime(time.strptime(
                    gather_time, time_format))
                )
        start_time = datetime.datetime.fromtimestamp(
                time.mktime(time.strptime(
                    start_time, time_format))
                )

        gather_location = '%s %s' % (
                f['gather_area'].value,
                f['gather_location'].value
                )

        
        coordx = 0.0
        coordy = 0.0
        accuracy = 0

        try:
            distance = int(f['distance'].value)
        except ValueError:
            distance = 0

        try:
            coordx = float(f['x'].value)
            coordy = float(f['y'].value)
            accuracy = int(f['acc'].value)
        except ValueError:
            raise
            sys.stderr.write("location %s could not be located\n" % (
                gather_location.encode('utf-8'))
                )

        actid = db.new_act(s.session.id, 
                f['subject'].value, 
                f['type'].value, 
                f['basecredit'].value,
                gather_time, 
                start_time, 
                gather_location, 
                coordx, 
                coordy, 
                accuracy, 
                distance,
                f['route'].value,
                f['descr'].value, 
                web.ctx.ip
                )

        newid = db.new_news(NEWS['newact'], uid = s.session.id, aid = actid)

        s.session.show_msg = True
        s.session.msg = "添加活动成功"
        web.seeother("activity?aid=%d" % actid)


class acts:

    def ERROR(self):
        s.session.show_msg = True
        s.session.msg = "操作错误"
        raise web.notfound()

    def GET(self):
        input = web.input(uid="None", act="None", offset="None")

        limit = app.page_limit
        offset = None
        acts = None
        act_size = 0
        act = None
        uid = -1
        try:
            offset = int(input.offset)
        except:
            offset = 0

        try:
            if input.uid != "None" and input.act != "None":
                uid = int(input.uid)
                act = input.act

                if act == 'wish':
                    acts = recover_datetime(db.get_user_wish_acts(uid, offset, limit))
                    act_size = db.get_user_wish_acts_size(uid)

                elif act == 'do':
                    acts = recover_datetime(db.get_user_do_acts(uid, offset, limit))
                    act_size = db.get_user_wish_acts_size(uid)

                elif act == 'own':
                    acts = recover_datetime(db.get_own_acts(uid, offset, limit))
                    i = {'k': 'uid', 'v': uid}
                    acts_size = db.get_count('activity', [i])

                elif act == "all":
                    acts = recover_datetime(db.get_update_acts(offset, limit))
                    act_size = db.get_count('activity')

                else:
                    raise
            else:
                raise
        except:
            raise
            self.ERROR()

        try:
            username, avatar = db.get_user_baseinfo(uid)
        except IndexError:
            self.ERROR()

        user = dict(zip(("uid", "name", "avatar"),\
                        (uid, username, avatar)))

        page_split = page_split_up(act_size, offset, limit, app.page_url)
        print page_split

        return s.render.acts(acts[:limit], offset, limit, act, user, page_split)



class admin(activity, add):

    def ERROR(self):
        s.session.show_msg = True
        s.session.msg = '活动错误'
        raise web.notfound()
    
    def GET(self):
        input = web.input(aid=None)

        aid = None
        act = None
        try:
            aid = int(input.aid)
            act = db.get_act(aid)
        except:
            self.ERROR()

        if act == None or s.session.id != act['uid']:
            self.ERROR()

        f = self.activity_form()
        f['subject'].value = act['subject']
        f['type'].value = act['type']
        f['basecredit'].value = act['basecredit']
        f['gather_day'].value = act['gathertime'].strftime("%m/%d/%Y")
        f['gather_hour'].value = act['gathertime'].strftime("%H")
        f['gather_min'].value = act['gathertime'].strftime("%M")
        f['start_day'].value = act['startime'].strftime("%m/%d/%Y")
        f['start_hour'].value = act['startime'].strftime("%H")
        f['start_min'].value = act['startime'].strftime("%M")
        f['gather_area'].value = act['gatherlocation'].split()[0]
        f['gather_location'].value = act['gatherlocation'].split()[1]
        f['x'].value = str(act['coordx'])
        f['y'].value = str(act['coordy'])
        f['acc'].value = str(act['accuracy'])
        f['distance'].value = act['distance']
        f['route'].value = act['route']
        f['descr'].value = act['descr']
        f['aid'].value = str(aid)
    
        joined = self.get_do(aid)
        discuss = self.get_discuss(aid)

        return s.render.act_admin(f, joined, discuss)

    def POST(self):

        f = self.activity_form()
        if not f.validates():
            s.session.show_msg = True
            s.session.msg = '管理活动失败'
            return s.render.add_activity(f)

        gather_time = '%s %s:%s' % (
                f['gather_day'].value, f['gather_hour'].value, f['gather_min'].value
                )

        start_time = '%s %s:%s' % (
                f['start_day'].value, f['start_hour'].value, f['start_min'].value
                )

        time_format = '%m/%d/%Y %H:%M'
        gather_time = datetime.datetime.fromtimestamp(
                time.mktime(time.strptime(
                    gather_time, time_format))
                )
        start_time = datetime.datetime.fromtimestamp(
                time.mktime(time.strptime(
                    start_time, time_format))
                )

        gather_location = '%s %s' % (
                f['gather_area'].value,
                f['gather_location'].value
                )

        coordx = 0.0
        coordy = 0.0
        accuracy = 0
        
        try:
            coordx = float(f['x'].value)
            coordy = float(f['y'].value)
            accuracy = int(f['acc'].value)
            distance = int(f['distance'].value)
        except ValueError:
            raise
            sys.stderr.write("location %s could not be located\n" % (
                gather_location.encode('utf-8'))
                )

        aid = int(f['aid'].value)
        actid = db.update_act(aid, s.session.id, f['subject'].value, 
                f['type'].value, f['basecredit'].value,
                gather_time, start_time, 
                gather_location, coordx, 
                coordy, accuracy, distance,
                f['route'].value,
                f['descr'].value, web.ctx.ip
                )

        s.session.show_msg = True
        s.session.msg = "管理活动成功"
        web.seeother("activity?aid=%d" % aid)


class fakeuser:

    def ERROR(self):
        s.session.show_msg = True
        s.session.msg = '用户错误'
        raise web.notfound()

    def check_permission(self, aid):
        act = db.get_act(aid)
        if act['uid'] != skate.session.id:
            raise "permission reject"

    def GET(self):
        input = web.input(aid=None, uid=None, op=None)
        aid = None
        uid = None
        op = None

        try:
            aid = int(input.aid)
            uid = int(input.uid)
            op = input.op

            db.handle_relation(uid, aid, RELATION[op])
        except:
            raise
            self.ERROR()

        web.seeother("act_admin?aid=%d" % aid)

